package cn.org.eshow.webapp.action;

import cn.org.eshow.bean.query.BillQuery;
import cn.org.eshow.common.ShopDataVar;
import cn.org.eshow.common.page.Page;
import cn.org.eshow.model.Bill;
import cn.org.eshow.service.BillManager;
import cn.org.eshow.util.OrderUtil;
import cn.org.eshow.util.PageUtil;
import cn.org.eshow.webapp.util.RenderUtil;
import org.apache.struts2.convention.annotation.AllowedMethods;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Results({ @Result(name = "input", location = "add"),
		@Result(name = "list", type = "redirect", location = ""),
		@Result(name = "success", type = "redirect", location = "view/${id}"),
		@Result(name = "redirect", type = "redirect", location = "${redirect}") })
@AllowedMethods({"search","view","save","update","delete"})
public class BillAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	@Autowired
	private BillManager billManager;

	private List<Bill> bills;
	private Bill bill = new Bill();
	private BillQuery query = new BillQuery();

	public String search() {
		Page<Bill> page = billManager.search(query);
		bills = page.getDataList();
		saveRequest("page", PageUtil.conversion(page));
		saveRequest("query",query);
		return LIST;
	}

	public String view() {
		if (id != null) {
			bill = billManager.get(id);
		}
		return NONE;
	}

	/**
	 * @return
	 * @throws Exception
	 */
	public String save() throws Exception {
		bill.setNo(OrderUtil.getOrderNo());
		bill = billManager.save(bill);
		saveMessage("添加成功");
		return REDIRECT;
	}

	/**
	 * @return
	 * @throws Exception
	 */
	public String update() throws Exception {
		Bill old = billManager.get(id);
		old = billManager.updateBill(old,bill);
		saveMessage("修改成功");
		return REDIRECT;
	}

	/**
	 * 针对"线下退款"才能删除
	 */
	public void delete() {
		Bill old = billManager.get(id);
		if (old != null && old.getType().equals(ShopDataVar.billType.平台线下退款.toString())) {
			billManager.remove(old);
			saveMessage("删除成功");
			RenderUtil.success("删除成功");
		} else {
			saveMessage("参数不正确");
			RenderUtil.failure("参数不正确");
		}
	}


	public List<Bill> getBills() {
		return bills;
	}

	public void setBills(List<Bill> bills) {
		this.bills = bills;
	}

	public Bill getBill() {
		return bill;
	}

	public void setBill(Bill bill) {
		this.bill = bill;
	}

	public BillQuery getQuery() {
		return query;
	}

	public void setQuery(BillQuery query) {
		this.query = query;
	}
}